package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Permission;
import cn.wolfcode.wms.mapper.PermissionMapper;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IPermissionService;
import cn.wolfcode.wms.utils.PageResult;
import cn.wolfcode.wms.utils.PermissionUtil;
import cn.wolfcode.wms.utils.RequirePermission;
import javafx.application.Application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper mapper;

    @Autowired
    private ApplicationContext ctx;

    @Override
    public void deleteByPrimaryKey(Long id) {

        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void insert(Permission entity) {
        mapper.insert(entity);
    }


    @Override
    public List<Permission> selectAll() {
        return mapper.selectAll();
    }


    @Override
    public PageResult query(QueryObject qo) {

        Long totalCount = mapper.queryForCount(qo);
        if (totalCount == 0){
            return new PageResult(qo.getPageSize());
        }
        List<Permission> listData = mapper.queryForList(qo);
        return new PageResult(listData,totalCount,qo.getCurrentPage(),qo.getPageSize());
    }
    /*
    加载权限表达式
     */
    @Override
    public void reload() {
        //0从数据库中查询所有的权限表达式
        List<String> expressions  = mapper.getExpression();

        //1.从spring容器中获取所用的controller对象
        Map<String, Object> beansWithAnnotation = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllerBeans = beansWithAnnotation.values();
        for (Object controllerBean : controllerBeans) {

            //2.获取所用的方法
            Method[] methods = controllerBean.getClass().getMethods();
            for (Method method : methods) {
            //3.判断当前的方法上是否含有requiredPermission标签
                if (method.isAnnotationPresent(RequirePermission.class)){
                    //4.若有,则将权限定名+方法名拼接为权限表达式
                    String expression = PermissionUtil.getExpression(method);

                    if (!expressions.contains(expression)){

                        //5.获取注解对象上的value值  为name
                        RequirePermission annotation = method.getAnnotation(RequirePermission.class);
                        String name = annotation.value();
                        Permission permission = new Permission();
                        permission.setExpression(expression);
                        permission.setName(name);
                        //6.保存到数据库中
                        mapper.insert(permission);
                    }
                }

            }
        }

    }


}
